//
//  STUserInfoViewController.swift
//  Story
//
//  Created by 汤泽川 on 2019/5/10.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import Kingfisher
import CLImagePickerTool
import PKHUD

class STUserInfoViewController: UIViewController {

    let disposeBag = DisposeBag()
    var imageIsChange = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        let userInfo = STUserService.shareInstance.currentUser.value!
        // 头像
        let avatarImageView = UIImageView()
        avatarImageView.kf.setImage(with: URL(string: userInfo.avatarUrl ?? ""), placeholder: #imageLiteral(resourceName: "user_default"))
        avatarImageView.layer.cornerRadius = 20
        avatarImageView.layer.masksToBounds = true
        self.view.addSubview(avatarImageView)
        avatarImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().inset(18)
            make.top.equalToSuperview().offset(statusBarHeight + 44 + 18)
            make.size.equalTo(CGSize(width: 40, height: 40))
        }
        let avatarLabel = UILabel()
        avatarLabel.text = "头像"
        avatarLabel.font = .systemFont(ofSize: 17)
        self.view.addSubview(avatarLabel)
        avatarLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(avatarImageView)
            make.left.equalToSuperview().offset(18)
        }
        let avatarLine = UIView()
        avatarLine.backgroundColor = UIColor.init(white: 0, alpha: 0.1)
        self.view.addSubview(avatarLine)
        avatarLine.snp.makeConstraints { (make) in
            make.top.equalTo(avatarImageView.snp_bottom).offset(18)
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        let changeAvatarBtn = UIButton()
        changeAvatarBtn.isEnabled = false
        self.view.addSubview(changeAvatarBtn)
        changeAvatarBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(avatarImageView)
        }
        changeAvatarBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.endEdit()
            let imagePicker = CLImagePickerTool()
            imagePicker.singleImageChooseType = .singlePictureCrop
            imagePicker.singleModelImageCanEditor = true
            imagePicker.singlePictureCropScale = 1
            imagePicker.cl_setupImagePickerWith(MaxImagesCount: 6, superVC: self) { (asset, cutImage) in
                avatarImageView.image = cutImage
                self.imageIsChange = true
            }
        }).disposed(by: disposeBag)
        
        let userName = STProfileItem(title: "用户名", content: userInfo.username, placeHolder: "请填写用户名")
        userName.contentFiled.isEnabled = false
        self.view.addSubview(userName)
        userName.snp.makeConstraints { (make) in
            make.top.equalTo(avatarLine.snp_bottom)
            make.left.right.equalToSuperview()
        }
        let email = STProfileItem(title: "邮箱", content: userInfo.email, placeHolder: "请填写邮箱")
        email.contentFiled.isEnabled = false
        self.view.addSubview(email)
        email.snp.makeConstraints { (make) in
            make.top.equalTo(userName.snp_bottom)
            make.left.right.equalToSuperview()
        }
        let introduce = STProfileItem(title: "简介", content: userInfo.introduce, placeHolder: "请填写个人简介")
        introduce.contentFiled.isEnabled = false
        self.view.addSubview(introduce)
        introduce.snp.makeConstraints { (make) in
            make.top.equalTo(email.snp_bottom)
            make.left.right.equalToSuperview()
        }
        let changeBtn = UIButton()
        changeBtn.setTitle("修改", for: .normal)
        changeBtn.setTitle("保存", for: .selected)
        changeBtn.setTitleColor(.blue, for: .normal)
        changeBtn.setTitleColor(.blue, for: .selected)
        changeBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.endEdit()
            changeBtn.isSelected = !changeBtn.isSelected
            if changeBtn.isSelected == true {
                introduce.contentFiled.isEnabled = true
                changeAvatarBtn.isEnabled = true
            } else {
                var image : UIImage? = nil
                if self.imageIsChange {
                    image = avatarImageView.image
                }
                HUD.show(.progress)
                STUserService.shareInstance.updateUserProfile(avatarImage: image?.jpegData(compressionQuality: 3), introduce: introduce.contentFiled.text ?? "").result(callBackWithData: { (newUserInfo, error) in
                    HUD.hide()
                    if newUserInfo != nil {
                        STUserService.shareInstance.updateUser(newUser: newUserInfo!)
                    }
                    if error != nil {
                        HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                    } else {
                        HUD.flash(.success)
                        introduce.contentFiled.isEnabled = false
                        changeAvatarBtn.isEnabled = false
                    }
                })
            }
        }).disposed(by: disposeBag)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: changeBtn)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        endEdit()
    }
    
    func endEdit() {
        self.view.endEditing(true)
    }
}

class STProfileItem: UIView {
    let titleLabel = UILabel()
    let contentFiled = UITextField()
    init(title : String, content : String?, placeHolder : String) {
        super.init(frame: CGRect.zero)
        titleLabel.text = title
        titleLabel.font = .systemFont(ofSize: 17)
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.top.bottom.equalToSuperview().inset(18)
            make.height.equalTo(17)
            make.left.equalToSuperview().offset(18)
        }
        contentFiled.font = .systemFont(ofSize: 17)
        contentFiled.text = content
        contentFiled.placeholder = placeHolder
        contentFiled.textAlignment = .right
        self.addSubview(contentFiled)
        contentFiled.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.height.equalTo(17)
            make.left.equalTo(titleLabel.snp_right).offset(18)
            make.right.equalToSuperview().offset(-18)
        }
        let line = UIView()
        line.backgroundColor = UIColor(white: 0, alpha: 0.1)
        self.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.right.left.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
